<template>
  <div>
    <div><h1>拼团活动(管理员)</h1></div>
    <div>
      <el-form :inline="true" :model="searchForm" class="demo-form-inline">
        <el-form-item label="关键字">
          <el-input
            v-model="searchForm.keyWord"
            placeholder="请输入品牌名称"
            clearable
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="loadList">搜索</el-button>
          <el-button type="primary" @click="showAddActive"
            >添加拼团活动</el-button
          >
        </el-form-item>
      </el-form>
    </div>
    <div>
      <el-table :data="tableData" stripe style="width: 100%">
        <el-table-column prop="activeId" label="ID" width="50" />
        <el-table-column prop="activeName" label="活动名称" width="120" />
        <el-table-column prop="groupNum" label="组团人数" width="100" />
        <el-table-column prop="beginTime" label="开始时间" width="150" />

        <el-table-column prop="endTime" label="截止时间" width="150" />
        <el-table-column prop="createTime" label="创建时间" width="150" />
        <el-table-column label="操作" width="240">
          <template #default="scope">
            <el-button type="primary" @click="JoinActiveshop(scope.row)"
              >参与拼团活动（商家参与）</el-button
            >
            <el-button type="primary" @click="onUpdateActive(scope.row)"
              >修改</el-button
            >
            <el-button type="primary" @click="onDeleteActive(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div style="margin-top: 20px">
      <div class="demo-pagination-block">
        <el-pagination
          v-model:current-page="searchForm.pageNum"
          v-model:page-size="searchForm.pageSize"
          :page-sizes="[2, 4, 6, 8]"
          :background="true"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    <div>
      <el-dialog v-model="dialogFormVisible" :title="title" width="500">
        <el-form :model="addForm" ref="ruleFormRef" :rules="rules">
          <el-form-item
            label="活动名称"
            :label-width="formLabelWidth"
            prop="brandNamee"
          >
            <el-input v-model="addForm.activeName" autocomplete="off" />
          </el-form-item>
          <el-form-item
            label="拼团人数"
            :label-width="formLabelWidth"
            prop="groupNum"
          >
            <el-input v-model="addForm.groupNum" autocomplete="off" />
          </el-form-item>
          <el-form-item
            label="开始时间"
            :label-width="formLabelWidth"
            prop="beginTime"
          >
            <el-date-picker
              v-model="addForm.beginTime"
              type="datetime"
              placeholder="请选择"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
          <el-form-item
            label="截止时间"
            :label-width="formLabelWidth"
            prop="endTime"
          >
            <el-date-picker
              v-model="addForm.endTime"
              type="datetime"
              placeholder="请选择"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogFormVisible = false">Cancel</el-button>
            <el-button
              type="primary"
              v-if="title == '添加拼团活动'"
              @click="submitForm(ruleFormRef)"
            >
              保存
            </el-button>
            <el-button
              type="primary"
              v-if="title == '修改拼团活动'"
              @click="submitForm1(ruleFormRef)"
            >
              修改
            </el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from "vue";
import {
  getActiveList,
  getAddActive,
  getUpdateActive,
  getDeleteByIdActive,
} from "../api/api";
import { ElMessage } from "element-plus";
import type { FormInstance, FormRules } from "element-plus";
import { useRouter } from "vue-router";
const router = useRouter();
const dialogFormVisible = ref(false);
const formLabelWidth = "140px";
const tableData = ref([]);
const total = ref(0);

const searchForm = ref({
  pageNum: 1,
  pageSize: 2,
  keyWord: null,
});

const title = ref("添加拼团活动");

const ruleFormRef = ref<FormInstance>();
const addForm = ref({
  activeId: null,
  activeName: "",
  beginTime: "",
  endTime: "",
  groupNum: 0,
});

//规则校验
const rules = reactive<FormRules>({
  activeName: [{ required: true, message: "请输入活动名称", trigger: "blur" }],
  groupNum: [{ required: true, message: "请输入拼团人数", trigger: "blur" }],
});

//跳转商家拼团
const JoinActiveshop = (row: any) => {
  //跳转商家活动列表
  router.push("/home/team/" + row.activeId);
};

//修改活动
const onUpdateActive = (row: any) => {
  Object.assign(addForm.value, row);
  title.value = "修改拼团活动";
  dialogFormVisible.value = true;
};

//删除活动
const onDeleteActive = (row: any) => {
  getDeleteByIdActive(row.activeId).then((res) => {
    if (res.data.code == 200) {
      ElMessage.success("删除成功");
      loadList();
    } else {
      ElMessage.error(res.data.msg);
    }
  });
};

//添加校验
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log("submit!");
      onAddActive();
    } else {
      console.log("error submit!", fields);
    }
  });
};
//修改校验
const submitForm1 = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log("submit!");
      onUpdateActive1();
    } else {
      console.log("error submit!", fields);
    }
  });
};

const onAddActive = () => {
  getAddActive(addForm.value).then((res) => {
    if (res.data.code == 200) {
      ElMessage.success("添加成功");
      dialogFormVisible.value = false;
      loadList();
    } else {
      ElMessage.error(res.data.msg);
    }
  });
};
const onUpdateActive1 = () => {
  getUpdateActive(addForm.value).then((res) => {
    if (res.data.code == 200) {
      ElMessage.success("修改成功");
      dialogFormVisible.value = false;
      loadList();
    } else {
      ElMessage.error(res.data.msg);
    }
  });
};

//显示添加框
const showAddActive = () => {
  title.value = "添加拼团活动";
  addForm.value = {
    activeId: null,
    activeName: "",
    beginTime: "",
    endTime: "",
    groupNum: 0,
  };
  dialogFormVisible.value = true;
};

//分页
const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`);
  searchForm.value.pageSize = val;
  loadList();
};
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`);
  searchForm.value.pageNum = val;
  loadList();
};

//查询列表
const loadList = () => {
  getActiveList(searchForm.value).then((res) => {
    if (res.data.code == 200) {
      tableData.value = res.data.data.records;
      total.value = res.data.data.total;
    }
  });
};

//初始化数据
onMounted(() => {
  loadList();
});
</script>

<style scoped></style>
